from grid_env_ideal_obs_repeat_task import *
from grid_agent import *
from checkpoint_utils import *
from maze_factory import *
from replay_config import *
import argparse
import json
import sys
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
import random
from sklearn.decomposition import PCA
from matplotlib.animation import FuncAnimation
from sklearn.cluster import KMeans
import threading
import mplcursors
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial.distance import pdist, squareform
from scipy.stats import pearsonr

def progress_bar(current, total, barLength = 100):
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * barLength - 1) + '>'
    spaces = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
    sys.stdout.flush()

@partial(jax.jit, static_argnums=(3,))
def model_forward(variables, state, x, model):
    """ forward pass of the model
    """
    return model.apply(variables, state, x)

@jit
def get_action(y):
    return jnp.argmax(y)
get_action_vmap = jax.vmap(get_action)

# load landscape and states from file
def load_task(pth = "./logs/task.json", display = True):
    # open json file
    with open(pth, "r") as f:
        data = json.load(f)
        landscape = data["data"]
        state = data["state"]
        goal = data["goal"]
        if display:
            print("state: ", state)
            print("goal: ", goal)
            print("landscape: ", landscape)
    return landscape, state, goal


def preprocess(trjs, max_length):
    processed_trjs = []
    for i in range(trjs.shape[0]):
        trj = trjs[i]
        if trj.shape[0] < max_length:
            last_element = trj[-1]
            processed_trj = np.concatenate([trj, np.repeat(last_element[np.newaxis,:], max_length - trj.shape[0], axis=0)], axis=0)
            processed_trjs.append(processed_trj)
        else:
            processed_trjs.append(trj)
    processed_trjs = np.array(processed_trjs)
    return processed_trjs
    
@jax.jit
def build_radiance_field(p):
    img = jnp.zeros((21, 21))
    top = 10
    bottom = 0
    effective_radius = 21*1.414
    px, py = p[0], p[1]

    x_coord_map = jnp.arange(img.shape[0])
    x_coord_map = jnp.repeat(x_coord_map[:, jnp.newaxis], img.shape[1], axis=1)

    y_coord_map = jnp.arange(img.shape[1])
    y_coord_map = jnp.repeat(y_coord_map[jnp.newaxis, :], img.shape[0], axis=0)
    
    dist = jnp.sqrt((x_coord_map - px)**2 + (y_coord_map - py)**2)
    img = jnp.where(dist < effective_radius,
                    (top - bottom) * (effective_radius - dist) / effective_radius + bottom,
                    img)
    return img

@jax.jit
def get_max_radiance_field(imgs):
    img = jnp.max(imgs, axis=0)
    return img

@jax.jit
def build_ridge(A):

    # 将 A 的第一个点对齐到 (10,10)
    A = A-A[0]+jnp.array([10,10])

    # 使用 jnp.map 来并行计算每个辐射场图像
    imgs = jax.vmap(build_radiance_field)(A)
    img = get_max_radiance_field(imgs)
    return img

build_ridge_vmap = jax.vmap(build_ridge)


def compute_trajectory_manifold():

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration

    nn_type = ''
    if rpl_config.nn_type == "vanilla":
        nn_type = "vanilla"
    elif rpl_config.nn_type == "gru":
        nn_type = "gru"

    def load_data_and_compute(nn_type, seq_len, redundancy, diverse_set_capacity):

        rnn_limit_rings_file_name = "./logs/rnn_limit_rings_of_best_estimation_" + nn_type + "_" + str(seq_len) + "_" + str(redundancy) + "_" + str(diverse_set_capacity) + ".npz"
        # 载入 npz 文件
        rnn_limit_rings_of_best_estimation_file = np.load(rnn_limit_rings_file_name)

        # 获取 npz 文件中的所有对象名称
        matrix_names = rnn_limit_rings_of_best_estimation_file.files

        rnn_limit_rings_of_best_estimation = []

        # 遍历对象名称，访问和操作每个矩阵对象
        for name in matrix_names:
            matrix = rnn_limit_rings_of_best_estimation_file[name]
            # 在这里进行对矩阵对象的操作
            # 例如，打印矩阵的形状
            # print(f"Matrix '{name}' shape: {matrix.shape}")
            rnn_limit_rings_of_best_estimation.append(matrix)

        # 求 rnn_limit_rings_of_best_estimation 的中心位置序列
        rnn_limit_rings_of_best_estimation_center = []
        for i in range(len(rnn_limit_rings_of_best_estimation)):
            rnn_limit_rings_of_best_estimation_center.append(np.mean(rnn_limit_rings_of_best_estimation[i], axis=(0,1)))
        rnn_limit_rings_of_best_estimation_center = np.array(rnn_limit_rings_of_best_estimation_center)
        print("rnn_limit_rings_of_best_estimation_center.shape: ", rnn_limit_rings_of_best_estimation_center.shape)

        file_name = "obs_data_" + nn_type + "_" + str(seq_len) + "_" + str(redundancy) + "_" + str(diverse_set_capacity) + ".npz"
        obs_file = np.load("./logs/" + file_name)
        diverse_set_trajectoies = obs_file["diverse_set_trajectoies"]
        print("diverse_set_trajectoies.shape: ", diverse_set_trajectoies.shape)

        return rnn_limit_rings_of_best_estimation_center, diverse_set_trajectoies
    
    configs = [

        [nn_type, 5, 1, 400],
        [nn_type, 6, 1, 400],
        [nn_type, 7, 1, 400],
        [nn_type, 8, 1, 400],
        [nn_type, 9, 1, 400],
        [nn_type, 10, 1, 400],
        [nn_type, 11, 1, 400],
        [nn_type, 12, 1, 400],
        [nn_type, 13, 1, 400],
        [nn_type, 14, 1, 400],
        
        ]

    diverse_set_trajectoies = []
    for i in range(len(configs)):
        _, dts = load_data_and_compute(configs[i][0], configs[i][1], configs[i][2], configs[i][3])
        diverse_set_trajectoies.append(dts)

    diverse_set_trajectoies_mat = []
    for i in range(len(diverse_set_trajectoies)):
        length_aligned_trj = preprocess(diverse_set_trajectoies[i], configs[-1][1])
        diverse_set_trajectoies_mat.append(length_aligned_trj)
        # print("diverse_set_trajectoies_mat[i].shape: ", diverse_set_trajectoies_mat[i].shape)
    diverse_set_trajectoies_mat0 = np.array(diverse_set_trajectoies_mat)
    diverse_set_trajectoies_mat = np.concatenate(diverse_set_trajectoies_mat, axis=0)
    print("diverse_set_trajectoies_mat.shape: ", diverse_set_trajectoies_mat.shape)
    print("diverse_set_trajectoies_mat0.shape: ", diverse_set_trajectoies_mat0.shape)

    diverse_set_trajectoies_mat_linear = diverse_set_trajectoies_mat.reshape(diverse_set_trajectoies_mat.shape[0], diverse_set_trajectoies_mat.shape[1]*diverse_set_trajectoies_mat.shape[2])
    print("diverse_set_trajectoies_mat_linear.shape: ", diverse_set_trajectoies_mat_linear.shape)

    """ version2: 对 ridge_images 进行 PCA
    """
    ridge_images = build_ridge_vmap(diverse_set_trajectoies_mat)
    print("RIs.shape: ", ridge_images.shape)
    # 将 RIs 从 (100, 21, 21) 转换成 (100, 441)
    ridge_images = ridge_images.reshape(ridge_images.shape[0], ridge_images.shape[1] * ridge_images.shape[2])
    print("RIs.shape: ", ridge_images.shape)

    # 对 ridge_images 进行 PCA
    pca = PCA()
    pca.fit(ridge_images)
    ridge_images_pca = pca.transform(ridge_images)

    ridge_images_pca_grouped = []
    for i in range(len(configs)):
        ridge_images_pca_grouped.append(ridge_images_pca[i*configs[i][3]:(i+1)*configs[i][3]])
        print("ridge_images_pca_grouped[i].shape: ", ridge_images_pca_grouped[i].shape)

    return copy.deepcopy(ridge_images_pca_grouped), copy.deepcopy(configs), copy.deepcopy(ridge_images), pca, copy.deepcopy(diverse_set_trajectoies_mat0)
    

if __name__ == "__main__":

    ridge_images_pca_grouped, configs, ridge_images, pca_RI, diverse_set_trajectoies_mat0 = compute_trajectory_manifold()

    print("shape of diverse_set_trajectoies_mat0 : ", diverse_set_trajectoies_mat0.shape)

    # diverse_set_trajectoies_mat0 是一个 10*400*14*2 的矩阵，其中 10 是 configs 的长度，400 是每个 configs 的 diverse_set_trajectoies 的数量，14 是每个 diverse_set_trajectoies 的长度，2 是每个 diverse_set_trajectoies 的维度
    # 现在需要用 matplotlib 绘制 10个 configs 的 diverse_set_trajectoies_mat0 的轨迹图，绘制到十张图像中，每张图像中有 400 条轨迹
    # 最后将这些图像并列显示

    fig, axs = plt.subplots(2, 5, figsize=(20, 10))
    axs = axs.ravel()
    for i in range(10):
        for j in range(400):
            diverse_set_trajectoies_mat0[i][j] = diverse_set_trajectoies_mat0[i][j] - diverse_set_trajectoies_mat0[i][j][0]
            # axs[i].plot(diverse_set_trajectoies_mat0[i][j][:,0], diverse_set_trajectoies_mat0[i][j][:,1], color='blue', alpha=0.1)
            # 使用随机颜色绘制路径而非同一颜色
            axs[i].plot(diverse_set_trajectoies_mat0[i][j][:,0], diverse_set_trajectoies_mat0[i][j][:,1], color=np.random.rand(3,), alpha=1)
            axs[i].set_xlim(-20, 20)
            axs[i].set_ylim(-20, 20)
        axs[i].set_title("length: " + str(i+5))

    plt.show()
    